<template>
  <view class="work-orders-page">
    <!-- 工单列表区域 -->
    <view class="orders-list-container">
      <z-paging
        ref="paging"
        v-model="ordersList"
        @query="queryList"
        :auto="true"
        :refresher-enabled="true"
        :loading-more-enabled="true"
        :empty-view-text="'暂无数据'"
        class="orders-list"
      >
        <template #top>
          <!-- 导航栏 -->
          <up-navbar title="我派发的工单" :autoBack="true" :fixed="true" bgColor="transparent" :border="false" placeholder/>
          
          <!-- 筛选器区域 -->
          <view class="filter-section">
            <view class="filter-row">
              <view class="filter-item">
                <picker mode="selector" :value="filters.typeIndex" :range="typeOptions" range-key="text" @change="onTypeChange">
                  <view class="picker-text">
                    <text>{{ filters.typeIndex >= 0 ? typeOptions[filters.typeIndex].text : '工单类型' }}</text>
                    <up-icon name="arrow-down" size="14"></up-icon>
                  </view>
                </picker>
              </view>
              <view class="filter-item">
                <picker mode="selector" :value="filters.statusIndex" :range="statusOptions" range-key="text" @change="onStatusChange">
                  <view class="picker-text">
                    <text>{{ filters.statusIndex >= 0 ? statusOptions[filters.statusIndex].text : '处理状态' }}</text>
                    <up-icon name="arrow-down" size="14"></up-icon>
                  </view>
                </picker>
              </view>
            </view>
            <view class="filter-row">
              <view class="filter-item">
                <picker mode="selector" :value="filters.priorityIndex" :range="priorityOptions" range-key="text" @change="onPriorityChange">
                  <view class="picker-text">
                    <text>{{ filters.priorityIndex >= 0 ? priorityOptions[filters.priorityIndex].text : '优先级' }}</text>
                    <up-icon name="arrow-down" size="14"></up-icon>
                  </view>
                </picker>
              </view>
              <view class="filter-item date-item">
                <picker mode="date" :value="filters.dateRange" @change="onDateChange">
                  <view class="picker-text">
                    <text>{{ filters.dateRange || '选择日期' }}</text>
                    <up-icon name="calendar" size="14"></up-icon>
                  </view>
                </picker>
              </view>
            </view>
            <view class="filter-row">
              <view class="filter-item search-item">
                <up-search
                  v-model="filters.searchKeyword"
                  :clearabled="true"
                  :showAction="true"
                  placeholder="请输入工单标题/指派人姓名"
                  @search="handleSearch"
                  @clear="handleClear"
                >
                  <template #action>
                    <up-button type="primary" size="small" @click="handleSearch">搜索</up-button>
                  </template>
                </up-search>
              </view>
            </view>
          </view>
        </template>
        <view class="orders-list-content">
          <work-order-item
            v-for="item in ordersList"
            :key="item.id"
            :work-order="item"
            @view="handleView"
            @track="handleTrack"
          />
        </view>
      </z-paging>
    </view>

    <!-- 工单详情弹窗 -->
    <up-popup v-model:show="showDetailModal" mode="bottom" :round="20">
      <view class="detail-modal">
        <view class="modal-header">
          <text class="modal-title">工单详情</text>
          <up-icon name="close" size="20" @click="closeDetailModal"></up-icon>
        </view>
        <view class="modal-content" v-if="selectedOrder">
          <view class="detail-item">
            <text class="detail-label">工单标题：</text>
            <text class="detail-value">{{ selectedOrder.title }}</text>
          </view>
          <view class="detail-item">
            <text class="detail-label">工单类型：</text>
            <text class="detail-value">{{ getOrderTypeText(selectedOrder.type) }}</text>
          </view>
          <view class="detail-item">
            <text class="detail-label">处理状态：</text>
            <text class="detail-value" :class="getStatusClass(selectedOrder.status)">{{ getStatusText(selectedOrder.status) }}</text>
          </view>
          <view class="detail-item">
            <text class="detail-label">指派给：</text>
            <text class="detail-value">{{ selectedOrder.assigneeName }}</text>
          </view>
          <view class="detail-item">
            <text class="detail-label">优先级：</text>
            <text class="detail-value" :class="getPriorityClass(selectedOrder.priority)">{{ getPriorityText(selectedOrder.priority) }}</text>
          </view>
          <view class="detail-item">
            <text class="detail-label">创建时间：</text>
            <text class="detail-value">{{ selectedOrder.createTime }}</text>
          </view>
          <view class="detail-item" v-if="selectedOrder.updateTime">
            <text class="detail-label">更新时间：</text>
            <text class="detail-value">{{ selectedOrder.updateTime }}</text>
          </view>
          <view class="detail-item" v-if="selectedOrder.description">
            <text class="detail-label">工单描述：</text>
            <text class="detail-value description">{{ selectedOrder.description }}</text>
          </view>
          <view class="detail-item" v-if="selectedOrder.result">
            <text class="detail-label">处理结果：</text>
            <text class="detail-value description">{{ selectedOrder.result }}</text>
          </view>
        </view>
      </view>
    </up-popup>

    <!-- 进度跟踪弹窗 -->
    <up-popup v-model:show="showTrackModal" mode="bottom" :round="20">
      <view class="track-modal">
        <view class="modal-header">
          <text class="modal-title">处理进度</text>
          <up-icon name="close" size="20" @click="closeTrackModal"></up-icon>
        </view>
        <view class="modal-content" v-if="selectedOrder">
          <view class="progress-timeline">
            <view class="timeline-item" v-for="(step, index) in getProgressSteps(selectedOrder)" :key="index" :class="{ active: step.active, completed: step.completed }">
              <view class="timeline-dot"></view>
              <view class="timeline-content">
                <text class="step-title">{{ step.title }}</text>
                <text class="step-time" v-if="step.time">{{ step.time }}</text>
                <text class="step-desc" v-if="step.description">{{ step.description }}</text>
              </view>
            </view>
          </view>
        </view>
      </view>
    </up-popup>
  </view>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import WorkOrderItem from './components/WorkOrderItem.vue'

// 筛选条件
const filters = reactive({
  typeIndex: 0,
  statusIndex: 0,
  priorityIndex: 0,
  dateRange: '',
  searchKeyword: ''
})

// 下拉选项数据
const typeOptions = [
  { value: '', text: '全部类型' },
  { value: 'maintenance', text: '设备维护' },
  { value: 'complaint', text: '投诉处理' },
  { value: 'inspection', text: '巡检任务' },
  { value: 'repair', text: '故障维修' },
  { value: 'other', text: '其他' }
]

const statusOptions = [
  { value: '', text: '全部状态' },
  { value: 'pending', text: '待处理' },
  { value: 'processing', text: '处理中' },
  { value: 'completed', text: '已完成' },
  { value: 'cancelled', text: '已取消' }
]

const priorityOptions = [
  { value: '', text: '全部优先级' },
  { value: 'high', text: '高优先级' },
  { value: 'medium', text: '中优先级' },
  { value: 'low', text: '低优先级' }
]

// 列表数据
const ordersList = ref([])
const paging = ref(null)

// 弹窗相关
const showDetailModal = ref(false)
const showTrackModal = ref(false)
const selectedOrder = ref(null)

// 获取工单列表数据
const queryList = async (pageNo, pageSize) => {
  try {
    // 获取筛选条件的值
    const params = {
      type: filters.typeIndex === 0 ? undefined : typeOptions[filters.typeIndex].value,
      status: filters.statusIndex === 0 ? undefined : statusOptions[filters.statusIndex].value,
      priority: filters.priorityIndex === 0 ? undefined : priorityOptions[filters.priorityIndex].value,
      dateRange: filters.dateRange,
      searchKeyword: filters.searchKeyword,
      pageNum: pageNo,
      pageSize
    }

    // TODO: 替换为实际的API调用
    const response = await new Promise(resolve => {
      setTimeout(() => {
        // 模拟数据
        let mockData = [
          {
            id: '1',
            title: '停车场设备维护',
            type: 'maintenance',
            status: 'processing',
            priority: 'high',
            assigneeName: '张三',
            assigneeId: 'user001',
            createTime: '2024-03-15 10:30:00',
            updateTime: '2024-03-15 14:20:00',
            description: '停车场闸机设备出现故障，需要及时维修',
            result: '已安排技术人员现场检修'
          },
          {
            id: '2',
            title: '用户投诉处理',
            type: 'complaint',
            status: 'completed',
            priority: 'medium',
            assigneeName: '李四',
            assigneeId: 'user002',
            createTime: '2024-03-15 09:15:00',
            updateTime: '2024-03-15 16:30:00',
            description: '用户反映收费异常问题',
            result: '已核实并退还多收费用，问题已解决'
          },
          {
            id: '3',
            title: '日常巡检任务',
            type: 'inspection',
            status: 'pending',
            priority: 'low',
            assigneeName: '王五',
            assigneeId: 'user003',
            createTime: '2024-03-15 08:00:00',
            description: '对停车场设施进行日常巡检'
          },
          {
            id: '4',
            title: '道闸故障维修',
            type: 'repair',
            status: 'processing',
            priority: 'high',
            assigneeName: '赵六',
            assigneeId: 'user004',
            createTime: '2024-03-15 07:45:00',
            updateTime: '2024-03-15 12:15:00',
            description: '入口道闸无法正常抬杆',
            result: '正在更换道闸控制器'
          },
          {
            id: '5',
            title: '系统升级维护',
            type: 'other',
            status: 'completed',
            priority: 'medium',
            assigneeName: '钱七',
            assigneeId: 'user005',
            createTime: '2024-03-15 06:30:00',
            updateTime: '2024-03-15 18:00:00',
            description: '停车管理系统版本升级',
            result: '系统升级完成，功能正常'
          }
        ]

        // 根据筛选条件过滤数据
        if (params.type) {
          mockData = mockData.filter(item => item.type === params.type)
        }
        if (params.status) {
          mockData = mockData.filter(item => item.status === params.status)
        }
        if (params.priority) {
          mockData = mockData.filter(item => item.priority === params.priority)
        }
        if (params.searchKeyword) {
          const keyword = params.searchKeyword.toLowerCase()
          mockData = mockData.filter(item => 
            item.title.toLowerCase().includes(keyword) ||
            item.assigneeName.toLowerCase().includes(keyword)
          )
        }
        if (params.dateRange) {
          mockData = mockData.filter(item => 
            item.createTime.includes(params.dateRange)
          )
        }

        resolve({
          data: mockData,
          total: mockData.length
        })
      }, 1000)
    })
    
    paging.value.complete(response.data)
  } catch (error) {
    console.error('获取工单列表失败:', error)
    uni.showToast({
      title: '获取数据失败',
      icon: 'none'
    })
    paging.value.complete(false)
  }
}

// 处理筛选条件变化
const onTypeChange = (e) => {
  filters.typeIndex = parseInt(e.detail.value)
  paging.value.reload()
}

const onStatusChange = (e) => {
  filters.statusIndex = parseInt(e.detail.value)
  paging.value.reload()
}

const onPriorityChange = (e) => {
  filters.priorityIndex = parseInt(e.detail.value)
  paging.value.reload()
}

const onDateChange = (e) => {
  filters.dateRange = e.detail.value
  paging.value.reload()
}

// 处理搜索
const handleSearch = () => {
  paging.value.reload()
}

// 处理清空搜索
const handleClear = () => {
  filters.searchKeyword = ''
  paging.value.reload()
}

// 处理查看详情
const handleView = (order) => {
  selectedOrder.value = order
  showDetailModal.value = true
}

// 处理跟踪进度
const handleTrack = (order) => {
  selectedOrder.value = order
  showTrackModal.value = true
}

// 关闭详情弹窗
const closeDetailModal = () => {
  showDetailModal.value = false
  selectedOrder.value = null
}

// 关闭进度跟踪弹窗
const closeTrackModal = () => {
  showTrackModal.value = false
  selectedOrder.value = null
}

// 获取工单类型文本
const getOrderTypeText = (type) => {
  const typeMap = {
    maintenance: '设备维护',
    complaint: '投诉处理',
    inspection: '巡检任务',
    repair: '故障维修',
    other: '其他'
  }
  return typeMap[type] || '其他'
}

// 获取状态样式类
const getStatusClass = (status) => {
  const statusMap = {
    pending: 'status-pending',
    processing: 'status-processing',
    completed: 'status-completed',
    cancelled: 'status-cancelled'
  }
  return statusMap[status] || 'status-pending'
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    pending: '待处理',
    processing: '处理中',
    completed: '已完成',
    cancelled: '已取消'
  }
  return statusMap[status] || '待处理'
}

// 获取优先级样式类
const getPriorityClass = (priority) => {
  const priorityMap = {
    high: 'priority-high',
    medium: 'priority-medium',
    low: 'priority-low'
  }
  return priorityMap[priority] || 'priority-medium'
}

// 获取优先级文本
const getPriorityText = (priority) => {
  const priorityMap = {
    high: '高',
    medium: '中',
    low: '低'
  }
  return priorityMap[priority] || '中'
}

// 获取进度步骤
const getProgressSteps = (order) => {
  const baseSteps = [
    { title: '工单创建', time: order.createTime, description: '工单已创建并指派', completed: true },
    { title: '开始处理', time: order.updateTime, description: '指派人员开始处理', completed: order.status !== 'pending', active: order.status === 'processing' },
    { title: '处理完成', time: order.status === 'completed' ? order.updateTime : '', description: order.result || '等待处理完成', completed: order.status === 'completed' }
  ]
  
  if (order.status === 'cancelled') {
    baseSteps[2] = { title: '工单取消', time: order.updateTime, description: '工单已取消', completed: true }
  }
  
  return baseSteps
}
</script>

<style lang="scss" scoped>
.work-orders-page {
  background: #f5f5f5;
  min-height: 100vh;
}

.orders-list-container {
  height: 100vh;
}

.orders-list {
  height: 100%;
}

.filter-section {
  background: #fff;
  padding: 24rpx;
  margin-bottom: 20rpx;
  
  .filter-row {
    display: flex;
    gap: 20rpx;
    margin-bottom: 20rpx;
    
    &:last-child {
      margin-bottom: 0;
    }
  }
  
  .filter-item {
    flex: 1;
    
    &.search-item {
      flex: 2;
    }
    
    .picker-text {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 16rpx 20rpx;
      background: #f8f9fa;
      border-radius: 8rpx;
      font-size: 28rpx;
      color: #333;
    }
  }
}

.orders-list-content {
  padding: 0 24rpx;
}

// 弹窗样式
.detail-modal,
.track-modal {
  background: #fff;
  border-radius: 20rpx 20rpx 0 0;
  max-height: 80vh;
  
  .modal-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 32rpx 32rpx 24rpx;
    border-bottom: 1rpx solid #f0f0f0;
    
    .modal-title {
      font-size: 36rpx;
      font-weight: 600;
      color: #333;
    }
  }
  
  .modal-content {
    padding: 32rpx;
    max-height: 60vh;
    overflow-y: auto;
  }
}

.detail-item {
  display: flex;
  margin-bottom: 24rpx;
  
  &:last-child {
    margin-bottom: 0;
  }
  
  .detail-label {
    font-size: 28rpx;
    color: #666;
    width: 160rpx;
    flex-shrink: 0;
  }
  
  .detail-value {
    font-size: 28rpx;
    color: #333;
    flex: 1;
    
    &.description {
      line-height: 1.5;
      word-break: break-all;
    }
    
    &.status-pending {
      color: #fa8c16;
    }
    
    &.status-processing {
      color: #1890ff;
    }
    
    &.status-completed {
      color: #52c41a;
    }
    
    &.status-cancelled {
      color: #ff4d4f;
    }
    
    &.priority-high {
      color: #ff4d4f;
      font-weight: 600;
    }
    
    &.priority-medium {
      color: #fa8c16;
      font-weight: 600;
    }
    
    &.priority-low {
      color: #52c41a;
      font-weight: 600;
    }
  }
}

.progress-timeline {
  .timeline-item {
    display: flex;
    margin-bottom: 32rpx;
    position: relative;
    
    &:last-child {
      margin-bottom: 0;
      
      &::after {
        display: none;
      }
    }
    
    &::after {
      content: '';
      position: absolute;
      left: 16rpx;
      top: 32rpx;
      width: 2rpx;
      height: 32rpx;
      background: #e8e8e8;
    }
    
    &.completed::after {
      background: #52c41a;
    }
    
    &.active::after {
      background: #1890ff;
    }
    
    .timeline-dot {
      width: 32rpx;
      height: 32rpx;
      border-radius: 50%;
      background: #e8e8e8;
      margin-right: 24rpx;
      flex-shrink: 0;
    }
    
    &.completed .timeline-dot {
      background: #52c41a;
    }
    
    &.active .timeline-dot {
      background: #1890ff;
    }
    
    .timeline-content {
      flex: 1;
      
      .step-title {
        font-size: 30rpx;
        font-weight: 600;
        color: #333;
        display: block;
        margin-bottom: 8rpx;
      }
      
      .step-time {
        font-size: 24rpx;
        color: #999;
        display: block;
        margin-bottom: 8rpx;
      }
      
      .step-desc {
        font-size: 26rpx;
        color: #666;
        line-height: 1.4;
        display: block;
      }
    }
  }
}
</style>